package com.ynr.salary.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ynr.dao.ISalaryDao;
import com.ynr.salary.service.ISalaryService;
import com.ynr.voucher.service.IVoucherSalaryService;
import com.ynr.voucher.utils.ExcelReader;

@Service
public class SalaryServiceImpl implements ISalaryService {

	private static final Logger logger = LoggerFactory.getLogger(SalaryServiceImpl.class);

	@Autowired
	private ISalaryDao salaryDao;
	
	@Autowired
	private IVoucherSalaryService voucherSalaryService;
	
	@Override
	public void uploadSalaryTable(String billDate, String companyId, String rootPath, MultipartFile multifile) {
		String filePath = rootPath + "/" + getGernarateFileName(multifile);
		try {
			FileUtils.copyInputStreamToFile(multifile.getInputStream(),
					new File(filePath));
		} catch (IOException e) {
			logger.error("SalaryServiceImpl uploadSalaryTable method create file error : {}", e.toString());
		}
		Map<String, Object> salaryMap = new HashMap<>();
		salaryMap.put("company_id", companyId);
		salaryMap.put("bill_date", billDate);
		salaryMap.put("file_path", filePath);
		salaryDao.insertSalary(salaryMap);
		List<Map<String, Object>> salaryContent = ExcelReader.parseSalaryExcel(filePath);
		for(Map<String, Object> item : salaryContent) {
			item.put("salary_id", String.valueOf(salaryMap.get("id")));
			salaryDao.insertSalaryDetail(item);
		}
		voucherSalaryService.processSalary(companyId, billDate, salaryContent);
		
	}
	
	private String getGernarateFileName(MultipartFile file) {
		Random rdm = new Random(System.currentTimeMillis());
		String extendName = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf(".") + 1);
		return System.currentTimeMillis() + Math.abs(rdm.nextInt())
				% 1000 + (extendName == null ? ".unknown" : "." + extendName);
	}
}
